<template>
    <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title" class="title-text">我的频道</div>
      <van-button
        class="edit-btn"
        type="danger"
        plain
        round
        size="mini"
        @click="isEdit = !isEdit"
      >{{ isEdit ? '完成' : '编辑' }}</van-button>
    </van-cell>
    <van-grid class="my-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in myChannel"
        :key="index"
        @click="onMyChannelClick(channel, index)"
      >
        <!--
          v-bind:class 语法
          一个对象，对象中的 key 表示要作用的 CSS 类名
                    对象中的 value 要计算出布尔值
                      true，则作用该类名
                      false，不作用类名
         -->
        <van-icon
          v-show="isEdit && !fiexChannels.includes(channel.id)"
          slot="icon"
          name="clear"
        ></van-icon>
        <span
          class="text"
          :class="{ active: index === active }"
          slot="text"
        >{{ channel.name }}</span>
      </van-grid-item>
    </van-grid>

    <!-- 频道推荐 -->
    <van-cell :border="false">
      <div slot="title" class="title-text">频道推荐</div>
    </van-cell>
    <van-grid class="recommend-grid" :gutter="10">
      <van-grid-item
        class="grid-item"
        v-for="(channel, index) in recommendChannels"
        :key="index"
        icon="plus"
        :text="channel.name"
        @click="onAddChannel(channel)"
      />
    </van-grid>
    <!-- /频道推荐 -->
  </div>
</template>


<script>
import { addUserChannel, getAllChannels,deleteUserChannel } from "@/api/channel";
import { setItem } from "@/utils/storage";
import { mapState } from "vuex";
export default {
  props: {
    myChannel:{
      type: Array,
      required: true,
    },
    active: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      AllChannels: [], //所有频道
      isEdit: false,
      fiexChannels: [0],
    };
  },
  created() {
    this.loadAllChannels();
  },
  methods: {
    async loadAllChannels() {
      try {
        const { data } = await getAllChannels();
        console.log('获取到的数据：',data);
        this.AllChannels = data.data.channels;
      } catch (err) {
        console.log(err);
        this.$toast("获取所有频道失败");
      }
    },
    async onAddChannel(channel) {
      // 用户添加频道数据的存贮分为登录存贮情况和未登录存贮情况
      try {
         // 用户添加频道
        this.myChannel.push(channel);
        if (this.user) {
          // 已登录则相关数据存储到线上
          await addUserChannel(
            {
              id: channel.id,
              seq: this.myChannel.length,
            },
          )
        } else {
          // 没有登录数据存储到本地
          setItem("TOUTIAO-CHANNEL", JSON.stringify(this.myChannel));
        }
        this.$toast('添加成功')
      } catch (err) {
        console.log(err)
        this.$toast('添加频道失败')
      }
    },
    onMyChannelClick(channel, index) {
      if (this.isEdit) {
        // 如果是推荐则不能删除
        if (this.fiexChannels.includes(channel.id)) {
          return;
        }
          this.myChannel.splice(index, 1);
        // 执行删除操作
        //如果是前面的一个，则更新激活频道的索引号
        // 同时对于删除操作，传值给父组件，告诉弹框显示状态依旧为true
        if (index <=this.active) {
          this.$emit("update-active", this.active - 1, true);
        }

        // 区分用户登录与否的持久化操作
        this.deleteChannel(channel);
      } else {
        // 执行切换对应页面操作
        // 自定义事件，来传递Index
        // 同时，传值给父组件，告诉弹框显示状态依旧为false
        this.$emit("update-active", index, false);
      }
    },
    // 删除用户的持久化操作，函数封装
    async deleteChannel(channel) {
     try{
        if(this.user){
        // 已登录则将数据更新到线上
        // 调用定义的接口方法
        console.log(channel.id)
        await deleteUserChannel(channel.id)
      }else{
        // 未登录，将数据更新到本地
        setItem('TOUTIAO-CHANNEL',JSON.stringify(this.myChannel))
      }
     this.$toast('删除成功')
     }catch(err){
       console.log(err)
        this.$toast('删除失败')
     }
    },
  },
  computed: {
    ...mapState(["user"]),
    recommendChannels() {
      // console.log(this.AllChannels)
      console.log(111,this.myChannel)
      return this.AllChannels.filter((item) => {
        // 里面的每一项取寻找符合条件的索引号再返回，
        return !this.myChannel.find((myChannel) => {
          return myChannel.id === item.id;
        });
      });
    },
  },
};
</script>

<style scoped lang="less">
.channel-edit {
  padding: 85px 0;

  .title-text {
    font-size: 32px;
    color: #333333;
  }

  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }

  /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }

  /deep/ .my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }

  /deep/ .recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }
}
</style>
